package com.NetSunWeiQin.chapter05.httpserver;

import java.io.*;
import java.nio.*;
import java.nio.charset.*;

/* 字符串形式的内容 */
public class StringContent implements Content {

    //    private static Charset charset = Charset.forName("GBK");
    private static Charset charset = Charset.defaultCharset();
    private String type;        // MIME type
    private String content;

    public StringContent(CharSequence c, String t) {
        content = c.toString();
        if (!content.endsWith("\n"))
            content += "\n";
//        type = t + "; charset=GBK";
        type = t + "; charset=utf-8";
    }

    public StringContent(CharSequence c) {
        this(c, "text/plain");
    }

    public StringContent(Exception x) {
        StringWriter sw = new StringWriter();
        x.printStackTrace(new PrintWriter(sw));
//        type = "text/plain; charset=GBK";
        type = "text/plain; charset=utf-8";
        content = sw.toString();
    }

    public String type() {
        return type;
    }

    private ByteBuffer byteBuffer = null;

    private void encode() {
        if (byteBuffer == null)
            byteBuffer = charset.encode(CharBuffer.wrap(content));
    }

    public long length() {
        encode();
        return byteBuffer.remaining();
    }

    public void prepare() {
        encode();
        byteBuffer.rewind();
    }

    public boolean send(ChannelIO cio) throws IOException {
        if (byteBuffer == null)
            throw new IllegalStateException();
        cio.write(byteBuffer);

        return byteBuffer.hasRemaining();
    }

    public void release() throws IOException {
    }
}

